from flask import (
    Blueprint, request, jsonify,session,make_response
)

from .db import get_db

import uuid
from datetime import datetime


bp = Blueprint('programs', __name__)

# 效验器
# 要求登录的装饰器
def login_required(func):
    def wrapper(*args, **kwargs):
        user_id = request.cookies.get('user_id',None)
        print(user_id)
        print(session)
        if user_id is None or user_id not in session or session[user_id] != user_id:
            response = make_response(jsonify({
            "msg": "请登录后操作",
            "code": 403
        }))
            response.status_code = 400  # 设置状态码为400
            return response
        return func(*args, **kwargs)
    return  wrapper

# select programs
@bp.route('/programs/getProgram',methods=('GET',), endpoint='getProgram')
def getProgram():
    # 获取查询参数program_id的值
    program_id = request.args.get('program_id')

    if program_id is None or len(program_id) < 10 or len(program_id) >20:
        return jsonify({
            "msg": "参数错误",
            "code": 403
        })

    db = get_db()
    cursor = db.cursor()

    try:
        # 执行数据库查询操作
        cursor.execute("SELECT * FROM programs WHERE program_id = %s",(program_id,))
        program = cursor.fetchall()

        cursor.execute("SELECT pl.* FROM process_list"
                                      " pl INNER JOIN process_program pp "
                                      "ON pl.process_id = pp.process_id "
                                      "WHERE pp.program_id = %s; ",(program_id,))
        process_list = cursor.fetchall()
        # 将查询结果转换为 JSON 格式
        cursor.close()
        db.close()

        if program is None or len(program) == 0:
            return jsonify({
                "msg": "未找到项目",
                "code": 403
            })
    except Exception as e:
        # 回滚事务
        db.rollback()
        db.close()
        print("获取失败:", str(e))
        return jsonify({
            "msg": "参数错误",
            "code": 403
        })

    res_process_list = []
    for row in process_list:
        process = {
            "process_id": row[0],  # 假设process_id在结果中的第二列
            "create_time": row[1],  # 假设create_time在结果中的第一列
            "title": row[2],  # 假设title在结果中的第三列
            "introduce": row[3],  # 假设introduce在结果中的第四列
            "imgs": [row[4], row[5], row[6], row[7], row[8]]
        }
        res_process_list.append(process)

        # 整理响应数据
    response = {
        "data": {
            "program_id": program[0][0],  # 假设program_id在结果中的第一列
            "create_time": program[0][1],
            "title": program[0][2],  # 假设title在结果中的第二列
            "introduction": program[0][3],  # 假设introduction在结果中的第三列
            "main_img": program[0][4],  # 假设main_img在结果中的第四列
            "process_list":res_process_list
        },
        "msg": "获取成功",
        "code": 200
    }
    return jsonify(response)

# add program
@bp.route('/programs/pullProgram',methods=('POST',) ,endpoint='pullProgram')
@login_required
def pullProgram():
    # 获取 POST 请求的参数
    data = request.json
    program_id = str(uuid.uuid4().hex)[:12]
    create_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    title = data['title']
    introduction = data['introduction']
    main_img = data['main_img']
    process_list = data['process_list']

    if data is None or program_id is None or len(program_id) < 10  :
        return  make_response(jsonify({
            "msg":"参数错误",
            "code":500
        }))

    if len(title) > 50 or len(introduction) > 300 or len(program_id) > 20 or len(main_img)>200:
        return  make_response(jsonify({
            "msg": "内容过长",
            "code": 403
                     }))

    if len(title) < 3 or len(introduction) < 10 :
        return make_response(jsonify({
            "msg":"标题或简介内容过短",
            "code":403
        }))

    db = get_db()
    cursor = db.cursor()
    try:
        # 检查
        cursor.execute("SELECT * FROM programs WHERE title = %s", (title,))
        program = cursor.fetchall()

        if program is not None and len(program) !=0:
            db.close()
            return make_response(jsonify({
                "msg": "项目已经存在",
                "code": 403
            }))

        # 新增项目
        cursor.execute("INSERT INTO programs (program_id,create_time,title,introduction,main_img) VALUES  (%s,%s,%s, %s, %s)", (program_id,create_time,title,introduction,main_img,))
        # 提交事务
        db.commit()

        for process in process_list:
            process_id = str(uuid.uuid4().hex)[:18]
            create_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            imgs = process['imgs']
            # 如果原始列表长度不足 5，则进行扩充
            if len(imgs) < 5:
                imgs.append('noImg')

            title = process['title']
            introduce= process['introduce']
            # 新增过程
            cursor.execute("INSERT INTO process_list (process_id,create_time,\
                           title,introduce,img1,img2,img3,img4,img5)\
                            VALUES  (%s,%s, %s, %s,%s,%s, %s, %s,%s )",
                           (process_id,create_time,title,introduce,imgs[0],imgs[1],imgs[2],imgs[3],imgs[4],))

            # 关系 提交
            cursor.execute("INSERT INTO process_program (program_id,process_id) VALUES  ( %s, %s)", (program_id,process_id,))
            # 提交事务
            db.commit()
        db.close()
    except Exception as e:
        # 回滚事务
        db.rollback()
        db.close()
        print("上传失败:", str(e))
        return make_response(jsonify({
            "msg": "上传失败",
            "code": 500
        }))

    return make_response(jsonify({
            "msg": "上传成功",
            "code": 200
        }))


# edit programs
@bp.route('/programs/editProgram',methods=('POST',) ,endpoint='editProgram')
@login_required
def editProgram():
    # 获取 POST 请求的参数
    data = request.json
    program_id = data['program_id']
    title = data['title']
    introduction = data['introduction']
    main_img = data['main_img']
    process_list = data['process_list']

    if data is None or program_id is None or len(program_id) < 10  :
        return  make_response(jsonify({
            "msg":"参数错误",
            "code":403
        }))


    if len(title) > 50 or len(introduction) > 300 or len(program_id) > 20 or len(main_img)>200:
        return make_response(jsonify({
            "msg": "内容过长",
            "code": 403
        }))


    if len(title) < 3 or len(introduction) < 10 :
        return make_response(jsonify({
            "msg":"标题或简介内容过短",
            "code":403
        }))


    db = get_db()
    cursor = db.cursor()

    try:
        # 检查
        cursor.execute("SELECT * FROM programs WHERE program_id = %s", (program_id,))
        program = cursor.fetchall()
        if program is None:
            db.close()
            return make_response(jsonify({
                "msg": "项目不存在,修改失败",
                "code": 403
            }))

        # 更新项目
        cursor.execute("UPDATE programs SET title = %s, introduction = %s, main_img = %s WHERE program_id = %s",
                       (title, introduction, main_img, program_id,))

        for process in process_list:
            process_id = process['process_id']

            imgs = process['imgs']
            # 如果原始列表长度不足 5，则进行扩充
            if len(imgs) < 5:
                imgs.append('noImg')
            title = process['title']
            introduce = process['introduce']
            #检查process_id是否存在
            cursor.execute("SELECT * FROM process_list WHERE process_id = %s", (process_id,))
            result = cursor.fetchall()

            if result is not None and len(result) != 0:
                # 更新过程
                cursor.execute(
                    "UPDATE process_list SET  title = %s, introduce = %s, img1 = %s, img2 = %s, img3 = %s, img4 = %s, img5 = %s WHERE process_id = %s",
                    ( title, introduce, imgs[0], imgs[1], imgs[2], imgs[3], imgs[4], process_id,))
            else:
                # 新增过程
                process_id = str(uuid.uuid4().hex)[:18]
                create_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                cursor.execute("INSERT INTO process_list (process_id,create_time,\
                                          title,introduce,img1,img2,img3,img4,img5)\
                                           VALUES  (%s,%s, %s, %s,%s,%s, %s, %s,%s )",
                               (process_id, create_time, title, introduce, imgs[0], imgs[1], imgs[2], imgs[3], imgs[4],))

                # 关系 提交
                cursor.execute("INSERT INTO process_program (program_id,process_id) VALUES  ( %s, %s)",
                               (program_id, process_id,))

            # 提交事务
        db.commit()
        db.close()
    except Exception as e:
        # 回滚事务
        db.rollback()
        db.close()
        print("修改失败:", str(e))
        return make_response( jsonify({
            "msg": "修改失败",
            "code": 500
        }))

    return make_response(jsonify({
            "msg": "修改成功",
            "code": 200
        }))


@bp.route('/programs/delProgram',methods=('POST',) ,endpoint='delProgram')
@login_required
def delProgram():
    # 获取 POST 请求的参数
    data = request.json
    program_id = data['program_id']
    process_id_list = data['process_id_list']
    db = get_db()
    cursor = db.cursor()
    # 删除整个项目包括程序
    if program_id is not None and len(program_id)>10 :
        try:
            # 删除项目
            cursor.execute("DELETE FROM programs WHERE program_id = %s", (program_id,))
            # 提交事务
            # 删除 process_list 表中的记录
            cursor.execute(
                "DELETE FROM process_list WHERE process_id IN (SELECT process_id FROM process_program WHERE program_id = %s)",
                (program_id,))
            # 关系删除
            cursor.execute("DELETE FROM process_program WHERE  program_id = %s",(program_id,))
            # 提交事务

            db.commit()
        except Exception as e:
            # 回滚事务
            db.rollback()
            db.close()
            print("删除失败:", str(e))
            return make_response(jsonify({
                "msg": "删除失败",
                "code": 500
            }))

        return make_response(jsonify({
            "code":200,
            "msg":"删除成功"
        }))


    # 只删除程序
    if  len(process_id_list) != 0 and program_id is None:
        for process_id in process_id_list:
            try:
                # 删除程序
                cursor.execute("DELETE FROM process_list WHERE process_id = %s",(process_id, ))
                # 关系删除
                cursor.execute("DELETE FROM process_program WHERE process_id = %s ", ( process_id,))
                # 提交事务
                db.commit()
            except Exception as e:
                # 回滚事务
                db.rollback()
                db.close()
                print("删除失败:", str(e))
                return make_response(jsonify({
                    "msg": "删除失败",
                    "code": 500
                }))

    db.close()

    return make_response( jsonify({
                "msg": "删除成功",
                "code": 200
            }))

@bp.route('/programs/delProcess',methods=('POST',) ,endpoint='delProcess')
@login_required
def delProcess():
    # 获取 POST 请求的参数
    data = request.json
    process_id = data['process_id']
    db = get_db()
    cursor = db.cursor()
    # 删除整个项目包括程序
    if process_id is not None and len(process_id)>10 :
        try:
            # 删除过程
            cursor.execute("DELETE FROM process_list WHERE process_id = %s", (process_id,))
            # 提交事务
            db.commit()
        except Exception as e:
            # 回滚事务
            db.rollback()
            db.close()
            print("删除失败:", str(e))
            return make_response(jsonify({
                "msg": "删除失败",
                "code": 500
            }))

        return make_response(jsonify({
            "code":200,
            "msg":"删除成功"
        }))

    db.close()
    return make_response( jsonify({
                "msg": "删除成功",
                "code": 200
            }))



# select programsList
@bp.route('/programs/programList',methods=('GET',) ,endpoint='programList')
def getProgramList():

    db = get_db()
    cursor = db.cursor()

    try:
        # 执行数据库查询操作
        cursor.execute("SELECT * FROM programs")
        program_list = cursor.fetchall()
        cursor.close()
        db.close()
    except Exception as e:
        # 回滚事务
        db.rollback()
        db.close()
        print("获取失败:", str(e))
        return make_response(jsonify({
            "msg": "删除成功",
            "code": 200
        }))
        return

    list = []
    for program in program_list :
        item = {}
        item["program_id"] = program[0]
        item["title"] = program[2]
        list.append(item)

    # 整理响应数据
    response = {
        "data": list,
        "msg": "获取成功",
        "code": 200
    }

    return jsonify(response)
